package com.ifp.opengate.boot;

import java.util.concurrent.Executor;

import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
import org.apache.dubbo.config.spring.context.annotation.EnableDubboConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.FilterType;
import org.springframework.context.annotation.ImportResource;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import com.ifp.adapter.process.JSONProcessor;
import com.ifp.opengate.boot.utils.SpringContextHolder;

/**
 * @author 灭霸 2018.10.21 springboot 改造.
 *
 */
@EnableDubbo
@EnableDubboConfig
@SpringBootApplication
@SpringBootConfiguration
@ImportResource("classpath:META-INF/conf/dubbov/dubbov.xml")
@ComponentScan(
    basePackages = {"com.ifp.opengate.boot", "com.ifp.adapter.process", "com.ifp.core.util", "com.ifp.adapter.process"},
    excludeFilters = {@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = {JSONProcessor.class})})
public class OpenGateApplication {

    @Value("${mq.pool.max}")
    private String mqPoolMax;

    @Value("${mq.pool.core}")
    private String mqPoolCore;

    public static void main(String[] args) {
        try {
            // 工作线程数调整（暂不使用）
            // System.setProperty("reactor.netty.ioWorkerCount",
            // String.valueOf(Math.max(Runtime.getRuntime().availableProcessors() * 3, 4)));
            // System.setProperty("reactor.netty.pool.maxConnections", "1000");
            // System.setProperty("reactor.netty.ioSelectCount", "1");
            SpringApplication.run(OpenGateApplication.class, args);
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

    @Bean(name = "mqThreadPool")
    public Executor mqThreadPoolExecutor() {
        ThreadPoolTaskExecutor mqThreadPool = new ThreadPoolTaskExecutor();
        mqThreadPool.setMaxPoolSize(Integer.parseInt(mqPoolMax));
        mqThreadPool.setCorePoolSize(Integer.parseInt(mqPoolCore));
        return mqThreadPool;
    }

    @Bean
    public SpringContextHolder springContextHolder() {
        return new SpringContextHolder();
    }
}